package cn.jvtc.course.management.system.utils;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * web层的工具类
 *
 * @author GaoFeng2017
 * @date 2017-12-07 20:28:11
 **/

public class WebUtils {
   /**
    * @description:
    * @author: GaoFeng2017
    * @date: 2017/12/7 21:26
    * @param: 
    * @return: 
    *
    */
    public void mapToBean(Map<String,String> map, Class clazz) {
        try{
            ConvertUtils.register(new Converter() {
                @Override
                public <T> T convert(Class<T> aClass, Object o) {
                    String value = (String)o;
                    if (o == null || "".equals(value.trim())) {
                        return null;
                    }
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    T result = null;
                    try {
                        result = (T)simpleDateFormat.parse(value);
                    } catch (ParseException e) {
                        e.printStackTrace();
                        throw  new RuntimeException(e);
                    }
                    return  result;
                }
            }, Date.class);
            Object bean = clazz.newInstance();
            BeanUtils.populate(bean,map);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
